﻿using System.Transactions;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using DotNetOpenAuth.AspNet;
using Microsoft.Web.WebPages.OAuth;
using WebMatrix.WebData;
using mscook.mvc.Filters;
using mscook.mvc.Models;
using mscook.core.services;
using mscook.mvc.Core;
using mscook.core.domain;
using System.Security.Principal;
using mscook.mvc.core;
using mscook.core.repositories;
using System.Collections.Generic;

namespace mscook.mvc.Controllers
{
    public class CommentController : BaseController
    {

        private ILoginUserService iLoginUserService;
        private ICommentRepository iCommentRepository;

        public CommentController(IActionBonusSettingService actionBonusSettingService, IResourceBonusSettingService resourceBonusSettingService, ILoginUserService loginUserService, ICommentRepository iCommentRepository)
            : base(actionBonusSettingService, resourceBonusSettingService, loginUserService)
        {
            this.iLoginUserService = loginUserService;
            this.iCommentRepository = iCommentRepository;
        }


        [HttpGet]
        public ActionResult Comment(string resourceId,string returnUrl,string start="")
        {
            CommentModel commentModel = new CommentModel();
            PageBreakHelper pageBreakHelper = new PageBreakHelper();
            pageBreakHelper.Init(start, "10");
            commentModel.Comments=iCommentRepository.GetByResourceIdByLimit(resourceId, pageBreakHelper.Start, pageBreakHelper.PerValue);
            commentModel.ResourceId = resourceId;
            commentModel.ReturnUrl = returnUrl;
            return View(commentModel);
        }

        [HttpPost]
        public ActionResult Comment(Comment comment,string resourceId,string parentComment="",string toLoginUser="",string returnUrl="/")
        {
            comment.FormLoginUser = CurrentUser;
            if (CurrentUser!=null)
            {
                if (!string.IsNullOrEmpty(toLoginUser))
                {
                    LoginUser loginUser = iLoginUserService.SelectLoginUserByLoginName(toLoginUser);
                    comment.ToLoginUser = loginUser;
                }

                if (!string.IsNullOrEmpty(parentComment))
                {
                    comment.ParentComment = iCommentRepository.Get(parentComment);
                }
            
                iCommentRepository.SaveOrUpdate(comment);
            }

            return Redirect(returnUrl);

        }

        public ActionResult CommentMore(string resourceId,string start = "2")
        {
            PageBreakHelper pageBreakHelper = new PageBreakHelper();
            pageBreakHelper.Init(start, "10");
            IList<Comment> comments = iCommentRepository.GetByResourceIdByLimit(resourceId, pageBreakHelper.Start, pageBreakHelper.PerValue);
            return View(comments);
        }

    }
}
